package com.briup.emdc.config.impl;

import com.briup.emdc.bean.Env;
import com.briup.emdc.config.Backup;
import com.briup.emdc.config.Configuration;
import com.briup.emdc.config.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;

/**
 * @author Kevin
 * @since 2024.04.11
 **/
public class BackupImpl implements Backup{
    private Log log;

    @Override
    public void save(final Collection<Env> coll,final String path,final boolean append){
        // 使用输出流在往文件中写数据的时候，
        // 默认就会覆盖原来已存在的文件
        try(ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(path,append))){
            oos.writeObject(coll);
            oos.flush();
        }catch(Exception e){
            log.error(e.getMessage());
        }
    }

    @Override
    public Collection<Env> load(final String path,final boolean delete){
        File file=new File(path);
        if(!file.exists()){
            return Collections.emptyList();
        }
        try(ObjectInputStream ois=new ObjectInputStream(Files.newInputStream(file.toPath()))){
            return (Collection<Env>)ois.readObject();
        }catch(Exception e){
            log.error(e.getMessage());
            return Collections.emptyList();
        }finally{
            if(delete){
                boolean deleted=file.delete();
                if(deleted) log.info(file+" 已被删除！");
            }
        }
    }

    @Override
    public void init(final Properties prop){}

    @Override
    public void configure(final Configuration conf) throws Exception{
        this.log = conf.getLogger();
    }
}
